import React, { Component } from 'react';
import ReactDom from 'react-dom';
import { FormattedMessage, injectIntl } from 'react-intl';
import { actions } from "mirrorx";
import { Table, Checkbox, Button, Modal, Icon, Radio, FormControl, Pagination, Select, Message } from "tinper-bee";
import moment from 'moment'
import DatePicker from "bee-datepicker";
import FormError from 'components/FormError';
import Grid from 'bee-complex-grid';
import SearchPanel from 'components/SearchPanel';
import RefComponent from 'components/RefComponent';
import FormList from 'components/FormList';
import multiSelect from "bee-table/build/lib/multiSelect.js";
import { deepClone, getValidateFieldsTrim, initValueString, renderEnable,ts2Formatter } from "utils";
import './index.less'

const MultiSelectTable = multiSelect(Table, Checkbox)

const FormItem = FormList.Item;

const columns1 = [
  { title: "单据号", dataIndex: "code", key: "code",width:140 },
  { title: "预算单元名称", dataIndex: "name", key: "name",width:350 },
  { title: "预算维度", dataIndex: "budgetDimensionName", key: "budgetDimensionName",width:140 },
  { title: "预算优先级", dataIndex: "budgetPriority", key: "budgetPriority", width:100 },
  { title: "隶属组织", dataIndex: "organizationName", key: "organizationName", width:170},
];

const columns1Child = [
  { title: "组织", dataIndex: "saleOrgName", key: "saleOrgName", width: 100},
  { title: "部门", dataIndex: "departmentName", key: "departmentName", width: 100},
  { title: "渠道", dataIndex: "channelName", key: "channelName", width: 100},
  { title: "客户", dataIndex: "customerName", key: "customerName", width: 100},
  { title: "门店", dataIndex: "terminalStoreName", key: "terminalStoreName", width: 100}
];
const searchField1 = [
  {
      enname: "code",
      zhname: "单据号",
      required: false,
      searchType: 'like',
      type: "FormControl",
      edit: true
  },
  {
      enname:"name",
      zhname:"预算单元名称",
      required: false,
      searchType: 'like',
      type: "FormControl",
      edit: true
  }
]

class GetDealModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      parentList:this.props.parentList
    }
  }

  componentWillReceiveProps(nextProps){
    this.setState({
      parentList:nextProps.parentList
    })
  }

  expandedRowRender = (record, index, indent) => {
    let parenteSelectIndex = index;
    return (
      <Grid
        columns={columns1Child}
        paginationObj={'none'}
        getSelectedDataFunc={(selectedList, record, index)=>this.getChildSelectedDataFunc(parenteSelectIndex,index,selectedList)}
        data={record.budgetUnitDetails}
        // className="innerTable"
      />
    );
  };

  haveExpandIcon = (record, index) => {
    //控制是否显示行展开icon，该参数只有在和expandedRowRender同时使用才生效
    if (index == 0) {
      return true;
    }
    return false;
  }

  GetDealModal = (delFlag) => {
    let {getDealCallback } = this.props;
    let { parentList } = this.state;

    if (delFlag) {
      parentList = parentList.filter(item=>{
        return item._checked
      })
      if(parentList.length == 0) {
        Message.create({ content: `请选择数据`, color: 'warning', duration: 10 });
        return;
      }
      let childList=[];
      parentList.map(item=> {
        item.budgetUnitDetails = item.budgetUnitDetails.filter(itemChild=>{
          return itemChild._checked;
        })
        childList.push.apply(childList,item.budgetUnitDetails);
      })
      
      let url = "/occ-fee/fee/budget-plans/process-convert-from-budget-unit";
      let param = {
        url: url,
        data: parentList[0],
      }
      actions.BudgetPlan.getDeal({ param: param, callback: getDealCallback });

    } else {
      this.props.closeGetDealModal();
    }
  }

  search = () => {
    this.props.form.validateFields((err, _values) => {
      let values = getValidateFieldsTrim(_values);

      for (let attr in values) {
        if(values[attr]===null || values[attr]==="" || (values[attr]&&values[attr].length == 0))
          delete values[attr];
      }

      this.getQuery(values);
      this.setState({ searchForm: values });
    });
  }

  /**
     * 重置 如果无法清空，请手动清空
     */
    reset = () => {
      let param = {};
      let _this = this;
      searchField1.map(item => {
          param[item.enname] = ""
          _this.props.form.setFieldsValue(param);
      })
  }

  getQuery = (values) => {
    let { openGetDealModal, origalData } = this.props;
    values.page = 0;
    values.size = origalData.size;
    let params = {};
    params.param = values;
    let searchField = searchField1;
    params.searchField = searchField;
    openGetDealModal(params);

  }

  getParentSelectedDataFunc = (selectedList, record, index, newData) => {
    let { parentList } = this.state;
    let _list = deepClone(parentList);
    //当第一次没有同步数据
    // if (this.oldData.length == 0) {
    //     this.oldData = deepClone(list);
    // }
    //同步list数据状态
    if (index != undefined) {
      _list[index]['_checked'] = !_list[index]['_checked'];
      _list[index].budgetUnitDetails.map(item=> {
        item["_checked"] = !item["_checked"];
      })
    } else {//点击了全选
      if (selectedList.length > 0) {//全选
        _list.map(item => {
          if (!item['_disabled']) {
            item['_checked'] = true
            item[index].budgetUnitDetails.map(itemChild=> {
              itemChild["_checked"] = true;
            })
          }
        });
      } else {//反选
        _list.map((item,index) => {
          if (!item['_disabled']) {
            item['_checked'] = false
            item[index].budgetUnitDetails.map(itemChild=> {
              itemChild["_checked"] = false;
            })
          }
        });
      }
    }
    this.setState({parentList:_list,parenteSelectIndex:index});
    sessionStorage.setItem("parentSelectList", JSON.stringify(_list));
  }

  getChildSelectedDataFunc = (parenteSelectIndex, index,selectData) => {
    let { parentList } = this.state;
    let _list = parentList[parenteSelectIndex].budgetUnitDetails;
    //同步list数据状态
    if (index != undefined) {
      _list[index]['_checked'] = !_list[index]['_checked'];
    } else {//点击了全选
      if (selectData.length > 0) {//全选
        _list.map(item => {
          if (!item['_disabled']) {
            item['_checked'] = true
          }
        });
        parentList[parenteSelectIndex]['_checked'] = true;
      } else {//反选
        _list.map(item => {
          if (!item['_disabled']) {
            item['_checked'] = false
          }
        });
        parentList[parenteSelectIndex]['_checked'] = false;
      }
    }
    if(selectData.length > 0) {
      parentList[parenteSelectIndex]['_checked'] = true;
    }else {
      parentList[parenteSelectIndex]['_checked'] = false;
    }
    parentList[parenteSelectIndex].budgetUnitDetails = _list;
    this.setState({parentList});
    sessionStorage.setItem("parentSelectList", JSON.stringify(parentList));
    // sessionStorage.setItem("childSelectList", JSON.stringify(selectedList));
  }

  getSelectedDataFunc = (selectedList, record, index, newData) => {
    sessionStorage.setItem("childSelectList", JSON.stringify(selectedList));
  }

  freshData = (pageIndex) => {
    let { origalData } = this.props;
    let param = {
      page: pageIndex - 1,
      size: origalData.size || 10
    }
    this.onPageSelect(param);
  }

  /**
   *
   * @param {*} index 跳转指定页数
   * @param {*} value 设置一页数据条数
   */
  onDataNumSelect = (index, value) => {
    let { origalData } = this.props;
    let param = {
      page: origalData.number || 0,
      size: value
    }
    this.onPageSelect(param);
  }

  /**
   *
   * @param {Number} value  pageIndex 或者 pageIndex
   * @param {Number} type 为0标识为 pageIndex,为1标识 pageSize
   */
  onPageSelect = (param) => {
    let { searchForm } = this.state;
    let { openGetDealModal} = this.props;
    let params = {};
    searchForm = Object.assign({}, searchForm, param);
    params.param = searchForm;
    let searchField = searchField1;
    params.searchField = searchField
    openGetDealModal(params);
  }

  renderFunc = (flag) => {
    let { queryParam, selectDataList = {} } = this.props;
    let { getFieldProps, getFieldError } = this.props.form;
    let dom = [];
    let childRowData = {};
    let self = this;
    let childType = "DataHeader";
    let required;
    searchField1.forEach((item, index) => {
      required = item.required;
      if (flag == 1 && index > 2) {
        return false;
      }
      if (flag == 2 && index < 3) {
        return true;
      }
      switch (item.type) {
        case 'FormControl':
          dom.push(<FormItem
            className="time"
            key={item.enname}
            required={item.required}
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            label={item.zhname}
          >
            <FormControl
              key={`${item.enname}${index}`}
              disabled={!item.edit}
              {...getFieldProps(`${item.enname}`, {
                initialValue: childRowData[item.enname] || "",
                rules: [{
                  required: required, message: "请输入",
                }],
              })}
            />
          </FormItem>);
          break;
        case 'InputNumber':
          dom.push(<FormItem
            className="time"
            key={item.enname}
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            required={item.required}
            label={item.zhname}
          >
            <InputNumber toThousands={true}
              key={`${item.enname}${index}`}
              iconStyle="one" step={1} disabled={!item.edit}
              {...getFieldProps(`${item.enname}`, {
                initialValue: (typeof childRowData[item.enname]) === "number" ? childRowData[item.enname] : 0,
                rules: [{
                  required: required, message: "请输入",
                }],
              })}
            />
          </FormItem>);
          break;
        case 'DatePicker':
          dom.push(<FormItem
            className="time"
            key={item.enname}
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            required={item.required}
            label={item.zhname}
          >
            <DatePicker
              key={`${item.enname}${index}`}
              format={item.format || format} disabled={!item.edit}
              {...getFieldProps(`${item.enname}`, {
                // initialValue: childRowData[item.enname] && moment(childRowData[item.enname]) || moment(),
                validateTrigger: 'onBlur',
                rules: [{
                  required: required,
                  message: '请选择',
                }],
              })}
            />
          </FormItem>);
          break;
        case 'RangePicker':
          dom.push(<FormItem
            className="time"
            key={item.enname}
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            required={item.required}
            label={item.zhname}
          >
            <RangePicker
              key={`${item.enname}${index}`}
              disabled={!item.edit}
              format={item.format}
              {...getFieldProps(`${item.enname}`, {
                initialValue: [moment(), moment()],
                validateTrigger: 'onBlur',
                rules: [{ required: required, message: '请选择', }],
              })}
            />
          </FormItem>);
          break;
        case 'RefComponent':
          dom.push(<FormItem
            className="time"
            key={item.enname}
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            required={item.required}
            label={item.zhname}
          >
            <RefComponent
              key={`${item.enname}${index}`}
              constparam={item.param}
              multiple={item.multiple || false}
              aliasparam={self.state.refStateParam}
              aliasfieldName={item.alias}
              title={item.zhname}
              refName={item.refname}
              childType={childType}
              fieldName={item.enname}
              clearMatchData={this.clearMatch}
              rules={[
                {
                  required: required,
                  message: '请选择',
                  pattern: item.required && /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                }
              ]}
              initialValue={childRowData[item.enname] || initValueString(childRowData[item.showname], childRowData[item.enname], item.required)}
              refTableOnClickSave={(refName, fieldName, data) => {
                if (item.offers) {
                  self.resetOfferRef(item, childType, childRowData);
                }
                if (item.cascadeName) {
                  //item 配置数据
                  //data 参照返回数据
                  //fieldName 参照Id字段
                  //childType 字表所属字段
                  self.calcuParm(item, data, fieldName, childType);
                }
              }}
              form={self.props.form}
            />
          </FormItem>);
          break;
        case 'Select':
          let options = selectDataList[item.code] || item.options;
          dom.push(<FormItem
            className="time"
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            required={item.required}
            label={item.zhname}
          >
            <Select
              key={`${item.enname}${index}`}
              disabled={!item.edit}
              {
              ...getFieldProps(`${item.enname}`, {
                initialValue: childRowData[item.enname] || "",
                rules: [{
                  required: required,
                  message: '请选择',
                }],
              })
              }
            >
              <Option value="">请选择</Option>
              {
                options && options.map((item, index) => {
                  return (
                    <Option key={index} value={item.code}>{item.name}</Option>
                  )
                })
              }

            </Select>
          </FormItem>);
          break;
        case 'Radio':
          dom.push(<FormItem
            key={item.enname}
            required={item.required}
            FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
            label={item.zhname}
          >
            <Radio.RadioGroup
              key={`${item.enname}${index}`}
              disabled={!item.edit}
              {
              ...getFieldProps(`${item.enname}`, {
                initialValue: childRowData[item.enname] || '1',
                rules: [{
                  required: required,
                  message: '请选择',
                }],
              }
              )}
            >
              {
                item.options && item.options.map((itemoption, index) => {
                  return (
                    <Radio
                      disabled={!item.edit}
                      key={index} value={itemoption.key}>{itemoption.value}</Radio>
                  )
                })
              }
            </Radio.RadioGroup>
          </FormItem>);
          break;
        default: break;
      }
    })
    return dom;
  }


  render() {
    let { onCallback, showGetDealModal, form, origalData } = this.props;
    let { getFieldProps, getFieldError } = this.props.form;
    let { parentList } = this.state;
    let { number, size, totalPages, totalElements } = origalData
    let { currentChildData } = this.state;
    let { createDate, billCode, promoter
    } = this.state.searchObj || {}
    let self = this;
    let dataNumSelect = [10,20,50,100,500];
    let paginationObj = {   // 分页
      activePage: number + 1,//当前页
      total: totalElements,//总条数
      size: size,
      dataNumSelect:dataNumSelect,
      dataNum:dataNumSelect.indexOf(size),
      items: totalPages,
      onSelect: this.freshData,
      onDataNumSelect: this.onDataNumSelect,
    }
    if(!parentList) return <></>;

    parentList.map((item, index) => {
      item.key = index;
    })

    let headchildren = <FormList size="sm">
      {self.renderFunc(1)}
    </FormList>
    return (
      <Modal
        show={showGetDealModal}
        // size={'xlg'}
        enforceFocus={false}
        width = '1100'
        className="getdeal"
        onHide={() => this.GetDealModal(false)} >
        <Modal.Header closeButton>
          <Modal.Title>拉单 <small>（点击行首 ' ＞ ' 的按钮可查看、选择明细）</small></Modal.Title>
        </Modal.Header>

        <Modal.Body>
          <SearchPanel
            form={form}
            reset={this.reset}
            onCallback={onCallback}
            intl={this.props.intl}
            search={this.search}
            headchildren={headchildren}>
            <FormList size="sm">
              {self.renderFunc(2)}
            </FormList>
          </SearchPanel>
          <MultiSelectTable
            className="expanded-table"
            columns={columns1}
            data={parentList}
            // defaultExpandAllRows={true}
            getSelectedDataFunc={this.getParentSelectedDataFunc}
            expandedRowRender={this.expandedRowRender}
            expandIconAsCell={true}
            scroll={{ y: 400 }}
            collapsedIcon={<Icon type='uf-anglearrowpointingtoright' />}
            expandedIcon={<Icon type='uf-treearrow-down' />}
          />
          <div className="center"><Pagination
            prev
            next
            maxButtons={5}
            boundaryLinks
            showJump={true}
            {...paginationObj}
          /></div>

        </Modal.Body>

        <Modal.Footer>
          <Button onClick={() => this.GetDealModal(false)} style={{ marginRight: 10 }}><FormattedMessage id="js.Ref.Ref224.0012" defaultMessage="关闭" /></Button>
          <Button colors="primary" onClick={() => this.GetDealModal(true)} ><FormattedMessage id="js.com.Pas.0005" defaultMessage="确定" /></Button>
        </Modal.Footer>
      </Modal>

    )
  }
}

export default FormList.createForm()(injectIntl(GetDealModal))